package initialize

import (
	"context"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	model "github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/plugin/plugin-tool/utils"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

func Api(ctx context.Context) {
	entities := []model.SysApi{
		// SysTask API
		{
			Path:        "/sysTask/createSysTask",
			Description: "新增sysTask表",
			ApiGroup:    "sysTask表",
			Method:      "POST",
		},
		{
			Path:        "/sysTask/deleteSysTask",
			Description: "删除sysTask表",
			ApiGroup:    "sysTask表",
			Method:      "DELETE",
		},
		{
			Path:        "/sysTask/deleteSysTaskByIds",
			Description: "批量删除sysTask表",
			ApiGroup:    "sysTask表",
			Method:      "DELETE",
		},
		{
			Path:        "/sysTask/updateSysTask",
			Description: "更新sysTask表",
			ApiGroup:    "sysTask表",
			Method:      "PUT",
		},
		{
			Path:        "/sysTask/findSysTask",
			Description: "根据ID获取sysTask表",
			ApiGroup:    "sysTask表",
			Method:      "GET",
		},
		{
			Path:        "/sysTask/getSysTaskList",
			Description: "获取sysTask表列表",
			ApiGroup:    "sysTask表",
			Method:      "GET",
		},
		{
			Path:        "/sysTask/runOneSysTask",
			Description: "任务运行一次",
			ApiGroup:    "sysTask表",
			Method:      "GET",
		},
		{
			Path:        "/sysTask/enableSysTask",
			Description: "激活任务",
			ApiGroup:    "sysTask表",
			Method:      "GET",
		},
		{
			Path:        "/sysTask/disableSysTask",
			Description: "暂停任务",
			ApiGroup:    "sysTask表",
			Method:      "GET",
		},
		{
			Path:        "/sysTask/removeSysTask",
			Description: "删除任务",
			ApiGroup:    "sysTask表",
			Method:      "GET",
		},
		// SysTaskLog API
		{
			Path:        "/sysTaskLog/createSysTaskLog",
			Description: "新增sysTaskLog表",
			ApiGroup:    "sysTaskLog表",
			Method:      "POST",
		},
		{
			Path:        "/sysTaskLog/deleteSysTaskLog",
			Description: "删除sysTaskLog表",
			ApiGroup:    "sysTaskLog表",
			Method:      "DELETE",
		},
		{
			Path:        "/sysTaskLog/deleteSysTaskLogByIds",
			Description: "批量删除sysTaskLog表",
			ApiGroup:    "sysTaskLog表",
			Method:      "DELETE",
		},
		{
			Path:        "/sysTaskLog/updateSysTaskLog",
			Description: "更新sysTaskLog表",
			ApiGroup:    "sysTaskLog表",
			Method:      "PUT",
		},
		{
			Path:        "/sysTaskLog/findSysTaskLog",
			Description: "根据ID获取sysTaskLog表",
			ApiGroup:    "sysTaskLog表",
			Method:      "GET",
		},
		{
			Path:        "/sysTaskLog/getSysTaskLogList",
			Description: "获取sysTaskLog表列表",
			ApiGroup:    "sysTaskLog表",
			Method:      "GET",
		},
	}
	utils.RegisterApis(entities...)
	
	// 插入 casbin_rule 权限数据
	CasbinRule(ctx)
}

// CasbinRule 插入 casbin_rule 表的权限数据
func CasbinRule(ctx context.Context) {
	// 定义权限规则数据，参考 sys_casbin.go 中的 AddPolicies 方法
	rules := [][]string{
		// SysTask API 权限
		{"888", "/sysTask/createSysTask", "POST"},
		{"888", "/sysTask/deleteSysTask", "DELETE"},
		{"888", "/sysTask/deleteSysTaskByIds", "DELETE"},
		{"888", "/sysTask/updateSysTask", "PUT"},
		{"888", "/sysTask/findSysTask", "GET"},
		{"888", "/sysTask/getSysTaskList", "GET"},
		{"888", "/sysTask/runOneSysTask", "GET"},
		{"888", "/sysTask/enableSysTask", "GET"},
		{"888", "/sysTask/disableSysTask", "GET"},
		{"888", "/sysTask/removeSysTask", "GET"},
		// SysTaskLog API 权限
		{"888", "/sysTaskLog/createSysTaskLog", "POST"},
		{"888", "/sysTaskLog/deleteSysTaskLog", "DELETE"},
		{"888", "/sysTaskLog/deleteSysTaskLogByIds", "DELETE"},
		{"888", "/sysTaskLog/updateSysTaskLog", "PUT"},
		{"888", "/sysTaskLog/findSysTaskLog", "GET"},
		{"888", "/sysTaskLog/getSysTaskLogList", "GET"},
	}

	// 转换为 CasbinRule 结构体，参考 AddPolicies 方法的实现
	var casbinRules []gormadapter.CasbinRule
	for i := range rules {
		// 检查是否已存在相同的权限规则
		var existingRule gormadapter.CasbinRule
		err := global.GVA_DB.Where("ptype = ? AND v0 = ? AND v1 = ? AND v2 = ?", 
			"p", rules[i][0], rules[i][1], rules[i][2]).First(&existingRule).Error
		
		if err == gorm.ErrRecordNotFound {
			// 记录不存在，添加到待插入列表
			casbinRules = append(casbinRules, gormadapter.CasbinRule{
				Ptype: "p",
				V0:    rules[i][0],
				V1:    rules[i][1],
				V2:    rules[i][2],
			})
		} else if err != nil {
			global.GVA_LOG.Error("查询 casbin_rule 失败", 
				zap.String("path", rules[i][1]), 
				zap.String("method", rules[i][2]), 
				zap.Error(err))
		} else {
			global.GVA_LOG.Info("casbin_rule 已存在，跳过插入", 
				zap.String("path", rules[i][1]), 
				zap.String("method", rules[i][2]))
		}
	}

	// 批量插入新的权限规则
	if len(casbinRules) > 0 {
		if err := global.GVA_DB.Create(&casbinRules).Error; err != nil {
			global.GVA_LOG.Error("批量插入 casbin_rule 失败", zap.Error(err))
		} else {
			global.GVA_LOG.Info("成功插入 casbin_rule", zap.Int("count", len(casbinRules)))
		}
	} else {
		global.GVA_LOG.Info("所有 casbin_rule 已存在，无需插入")
	}
}